package cz.wors.android.custom.rideshare;

import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class RideShareActivity extends MyParentActivity
{
	// debug mode
	public static final boolean DEBUG = false;
	
	// generovani checkboxu
	public static final int CHECKBOX_START_ID = 100;
	public static final int ROW_START_ID = 200;
	public static final int CHECKBOX_WIDTH = 140;
	public static final int CHECKBOX_HEIGHT = 40;
	public int CHECKBOX_COUNT = 0;
	
	// generovani popup window
	public static final int SPINNER_CONTACT = 301;
	public static final int SPINNER_DRIVER = 302;
	public static final int EDIT_AMOUNT = 303;
	
	// generovani tabulek pro bilance
	public static final int TABLE_BACKGROUND = 0xffaaaaaa;
	public static final int TITLE_BACKGROUND = 0xff555555;
	public static final int SUBTITLE_BACKGROUND = 0xff222222;
	public static final int CELL_BACKGROUND = 0xff000000;
	public static final int ROW_HEIGHT = 30;
	public static final int ROW_WIDTH = 288;
	
	// generovani historie
	public Boolean HISTORY_JIZDY_VISIBLE = false;
	public Boolean HISTORY_PLATBY_VISIBLE = false;
	public String HISTORY_DRIVER = "";
	public String HISTORY_PASSENGER = "";
	
	// generovani nastaveni
	public int SETTINGS_NAME_START_ID = 400;
	public int SETTINGS_DRIVER_CHECK_START_ID = 500;
	public int SETTINGS_PRICE_START_ID = 600;
	public int SETTINGS_EDIT_BTN_START_ID = 700;
	public int SETTINGS_EDIT_BTN2_START_ID = 800;
	
	// generovani menu
	public static final int TAB_JIZDY = 0;
	public static final int TAB_PENIZE = 1;
	public static final int TAB_NASTAVENI = 2;
	
	ScrollView main;
	
	PopupWindow popup_window;
	LinearLayout popup;
	DBAdapter db;
	
	TextView pole_datum;
	Calendar zobrazeno;

	public Calendar getZobrazeno() {
		return zobrazeno;
	}

	public Date getNow() {
		return new Date();
	}

	public void setZobrazeno(Date datum) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(datum);
		this.zobrazeno = cal;
		
		pole_datum.setText(DateFormat.getLongDateFormat(getApplicationContext()).format(datum));
		
		//pole_datum.setText(getDen()+"."+getMesic()+" "+getRok());
		setBtnText(datum);
		setDefaultValues();
	}
	
	public String getDen() {
		String den = ""+zobrazeno.get(Calendar.DAY_OF_MONTH);
		if (den.length() == 1) {
			return "0"+den;
		}
		else {
			return ""+den;
		}
	}
	
	public String getMesic() {
		int resId = getResources().getIdentifier(KalendarTools.mesice[zobrazeno.get(Calendar.MONTH)], "string", getPackageName());
		return getString(resId);
	}
	
	public String getCisloMesice() {
		Integer cislo = zobrazeno.get(Calendar.MONTH)+1;
		String string = cislo.toString();
		if (string.length() == 1) {
			return "0"+string;
		}
		else {
			return ""+string;
		}
	}
	
	public String getRok() {
		return ""+zobrazeno.get(Calendar.YEAR);
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		main = (ScrollView) findViewById(R.id.main);
		
		db = new DBAdapter(this);
		
		db.open();
		// smazani databaze a jeji znovuvytvoreni
		//db.reload();
		
		if (db.getContactCount() <= 0)
		{
			showToast(getString(R.string.msg_creating_from_template));
			vlozDataZeSablonyDoDB();
		}
		db.close();
		
		// generuj TabView
		TabHost mTabHost = getTabHost();
		
		mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(getString(R.string.tab_ways)).setContent(R.id.tab1));
        mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(getString(R.string.tab_money)).setContent(R.id.tab2));
        mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator(getString(R.string.tab_settings)).setContent(R.id.tab3));
		
		generateLayout();
		
		pole_datum = (TextView) findViewById(R.id.date);
		
		setZobrazeno(getNow());
    }
	
	public void nastavMenu(Menu menu, int tab)
	{
		menu.clear();
		
		switch (tab)
		{
			case TAB_JIZDY:
				menu.add(getString(R.string.menu_new_contact));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new NovyCestujiciMenuListener());
				
				menu.add(getString(R.string.menu_quit));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new UkoncitMenuListener());
				
				break;
			case TAB_PENIZE:
				menu.add(getString(R.string.menu_new_payment));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new ProvedPlatbuMenuListener());
				
				menu.add(getString(R.string.menu_quit));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new UkoncitMenuListener());
				
				break;
			case TAB_NASTAVENI:
				menu.add(getString(R.string.menu_new_contact));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new NovyCestujiciMenuListener());
				
				menu.add(getString(R.string.menu_quit));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new UkoncitMenuListener());
				
				break;
			default:
				menu.add(getString(R.string.menu_quit));
				menu.getItem(menu.size()-1).setOnMenuItemClickListener(new UkoncitMenuListener());
				
				break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		nastavMenu(menu, getTabHost().getCurrentTab());
		
		return true;
	}
	
	public void setBtnText(Date datum)
	{
		int position = 0;
		for (int i=1; i <= 6; i++)
		{
			for (String den: KalendarTools.dny)
			{
				String btn_id = den+"_"+i;
				
				int resID = getResources().getIdentifier(btn_id, "id", "cz.wors.android.custom.rideshare");
				KalendarButton btn = (KalendarButton) findViewById(resID);
				
				Date position_date = KalendarTools.getDateOnPosition(datum, position);
				Integer btn_den = KalendarTools.getDayOnPosition(datum, position);
				btn.setText(btn_den.toString());
				
				Calendar btn_cal = Calendar.getInstance();
				btn_cal.setTime(position_date);
				
				Calendar now_cal = Calendar.getInstance();
				now_cal.setTime(getNow());
				
				Calendar zobraz_cal = Calendar.getInstance();
				zobraz_cal.setTime(datum);
				
				if(btn_cal.get(Calendar.DAY_OF_MONTH) == zobraz_cal.get(Calendar.DAY_OF_MONTH) 
					&& btn_cal.get(Calendar.MONTH) == zobraz_cal.get(Calendar.MONTH) 
					&& btn_cal.get(Calendar.YEAR) == zobraz_cal.get(Calendar.YEAR))
				{
					btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_red));
					btn.setTextColor(Color.WHITE);
				}
				else if (btn_cal.get(Calendar.DAY_OF_MONTH) == now_cal.get(Calendar.DAY_OF_MONTH) 
					&& btn_cal.get(Calendar.MONTH) == now_cal.get(Calendar.MONTH) 
					&& btn_cal.get(Calendar.YEAR) == now_cal.get(Calendar.YEAR))
				{
					btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_orange));
					btn.setTextColor(Color.WHITE);
				}
				else if (KalendarTools.getColorOnPosition(datum, position))
				{
					btn.setTextColor(Color.WHITE);
					btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_gray));
				}
				else
				{
					btn.setTextColor(Color.GRAY);
					btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_gray));
				}
				btn.position = position;
				
				position ++;
			}
		}
	}
	
	/*
	 * Nastavuje vychozi hodnoty podle hodnot v databazi
	 */
	public void setDefaultValues()
	{
		String datum = getRok()+"-"+getCisloMesice()+"-"+getDen();
		
		if (RideShareActivity.DEBUG) {
			Log.i("SET DEFAULT VALUES", "Datum "+datum);
		}
		
		RadioButton tam_btn = (RadioButton) findViewById(R.id.tam);
		RadioButton zpet_btn = (RadioButton) findViewById(R.id.zpet);
		
		String smer;
		if (zpet_btn.isChecked()) {
			smer = getString(R.string.direction_back);
		}
		else {
			smer = getString(R.string.direction_forward);
		}
		
		if (RideShareActivity.DEBUG) {
			Log.i("SET DEFAULT VALUES", "Směr "+smer);
		}
		
		String[] passengers = null;
		String driver = null;
		db.open();
		Cursor way = db.getWayOnDate(datum,smer);
		if (way != null)
		{
			passengers = db.getPassengersOnWay(way);
			driver = db.getDriverOnWay(way);
		}
		way.close();
		db.close();
		
		if (driver == null || passengers == null)
		{
			if (RideShareActivity.DEBUG) {
				Log.i("SET DEFAULT VALUES", "Žádná cesta");
			}
			CheckBox all = (CheckBox) findViewById(CHECKBOX_START_ID);
			if (RideShareActivity.DEBUG) {
				Log.i("ALL PICK CALL", "ALL je na "+all.isChecked());
			}
			if (!all.isChecked()) {
				all.setChecked(true);
			}
			all.setChecked(false);
			if (RideShareActivity.DEBUG) {
				Log.i("ALL PICK END", "ALL je na "+all.isChecked());
			}
			return;
		}
		
		if (RideShareActivity.DEBUG) {
			Log.i("SET DEFAULT VALUES", "Řidič "+driver);
		}
		
		// nastav combobox
		Spinner driver_select = (Spinner) findViewById(R.id.driver_select);
		db.open();
		String[] items = db.getAllDrivers();
		db.close();
		for (int i=0; i<items.length; i++)
		{
			if (items[i].equals(driver)) {
				driver_select.setSelection(i);
			}
		}
		
		for (int j=0; j<passengers.length; j++)
		{
			if (RideShareActivity.DEBUG) {
				Log.i("SET DEFAULT VALUES", "Pasažér "+passengers[j]);
			}
		}
		// nastav checkboxy
		if (RideShareActivity.DEBUG) {
			Log.i("SET DEFAULT VALUES", "Checking passengers boxes");
		}
		for (int i=1; i<CHECKBOX_COUNT; i++)
		{
			int cb_id = CHECKBOX_START_ID+i;
			CheckBox check = (CheckBox) findViewById(cb_id);
			
			if (check.isChecked()) {
				check.setChecked(false);
			}
			
			if (RideShareActivity.DEBUG) {
				Log.i("SET CHECK BOX", "Checking box with name "+check.getText()+", setting to FALSE");
			}
			
			for (int j=0; j<passengers.length; j++)
			{
				if (RideShareActivity.DEBUG) {
					Log.i("COMPARE TEXT", "Comparing texts: "+check.getText()+"(checkbox), "+passengers[j]+"(passenger)");
				}
				if (check.getText().toString().equals(passengers[j]))
				{
					check.setChecked(true);
					if (RideShareActivity.DEBUG) {
						Log.i("SET CHECKBOX", "Setting "+passengers[j]+"'s checkbox to TRUE");
					}
				}
			}
		}
	}
	
	public String nextMonth()
	{
		Calendar kalendar = Calendar.getInstance();
		kalendar.setTime(zobrazeno.getTime());

		kalendar.add(Calendar.MONTH, +1);

		setZobrazeno(kalendar.getTime());
		
		return getMesic()+" "+getRok();
	}
	
	public String prevMonth()
	{
		Calendar kalendar = Calendar.getInstance();
		kalendar.setTime(zobrazeno.getTime());

		kalendar.add(Calendar.MONTH, -1);

		setZobrazeno(kalendar.getTime());
		
		return getMesic()+" "+getRok();
	}
	
	public class ChangeMonthListener implements OnClickListener
	{
		public String type;

		public ChangeMonthListener(String type) {
			this.type = type;
		}
		
		public void onClick(View v) {
			if ("prev".equals(type)) {
				prevMonth();
			}
			if ("next".equals(type)) {
				nextMonth();
			}
			
			// prekreslit bilance
			generateBilanceTables();
			generateBilanceHistory("jizdy");
		}
	}

	private void setDriversToSpinner(Spinner spinner) {
		// najit ridice
		db.open();
		String[] items = db.getAllDrivers();
		db.close();
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}

	private void setContactsToSpinner(Spinner spinner) {
		// najit ridice
		db.open();
		String[] items = db.getAllContacts();
		db.close();
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}
	
	public class CalendarOnClickListener implements OnClickListener {
		private final int position;

		public CalendarOnClickListener(int position)  
		{
			this.position = position;  
		}  

		public void onClick(View v)  
		{
			setZobrazeno(KalendarTools.getDateOnPosition(zobrazeno.getTime(), position));
		}
	}
	
	public class AllPickOnClickListener implements OnCheckedChangeListener
	{
		public void onCheckedChanged(CompoundButton btn, boolean checked) {
			if (RideShareActivity.DEBUG) {
				Log.i("ALL PICK EVENT","Nastavuji all na "+checked);
			}
			
			if (RideShareActivity.DEBUG) {
				Log.i("ALL PICK EVENT","Počet checkboxů: "+(CHECKBOX_COUNT));
			}
			switch(btn.getId())
			{
				case CHECKBOX_START_ID:
					
					for (int i=1; i<CHECKBOX_COUNT; i++)
					{
						int cb_id = CHECKBOX_START_ID+i;
						CheckBox checkbox = (CheckBox) findViewById(cb_id);
						if (RideShareActivity.DEBUG) {
							Log.i("ALL PICK EVENT","Checkbox "+checkbox.getText()+" je "+checkbox.isChecked());
						}
						// pokud zaskrtavame, zaskrtneme nezaskrtnute, pokud rusime, zrusime zaskrtnute
						if ((checked && !checkbox.isChecked()) || (!checked && checkbox.isChecked()))
						{
							if (RideShareActivity.DEBUG) {
								Log.i("ALL PICK EVENT","Nastavuji "+checkbox.getText()+" na "+checked);
							}
							checkbox.setChecked(checked);
						}
					}
					
					break;
			}
		}	
	}
	
	public class NoAllPickOnClickListener implements OnCheckedChangeListener
	{
		public void onCheckedChanged(CompoundButton btn, boolean checked) {
			
			if (RideShareActivity.DEBUG) {
				Log.i("NO ALL PICK EVENT","Počet checkboxů: "+(CHECKBOX_COUNT));
			}
			CheckBox all = (CheckBox) findViewById(CHECKBOX_START_ID);
			
			// zjistime stavy vsech checkboxu
			int[] zaskrtnute = new int[CHECKBOX_COUNT-1];
			int count = 0;

			for (int i=1; i<CHECKBOX_COUNT; i++)
			{
				if (RideShareActivity.DEBUG) {
					Log.i("NO ALL PICK EVENT","Vybírám checkbox "+(CHECKBOX_START_ID+i));
				}
				CheckBox ch = (CheckBox) findViewById(CHECKBOX_START_ID+i);
				if (ch.isChecked())
				{
					zaskrtnute[count] = ch.getId();
					if (RideShareActivity.DEBUG) {
						Log.i("NO ALL PICK EVENT","Zaskrtnute("+count+") = "+ch.getId());
					}
					count ++;
				}
			}
			if (checked)
			{
				if (RideShareActivity.DEBUG) {
					Log.i("NO ALL PICK EVENT","Checked je TRUE");
				}
				// projdeme vsechny checkboxy a pokud jsou zaskrtnute, zaskrtneme i hlavni
				for (int i=0; i<zaskrtnute.length; i++)
				{
					if (RideShareActivity.DEBUG) {
						Log.i("NO ALL PICK EVENT","Zaskrtnute["+i+"] = "+zaskrtnute[i]);
					}
					if (zaskrtnute[i] <= 0)
					{
						if (RideShareActivity.DEBUG) {
							Log.i("NO ALL PICK EVENT","Zaskrtnute["+i+"] < 0  => RETURN");
						}
						return;
					}
				}
				all.setChecked(true);
			}
			else
			{
				if (RideShareActivity.DEBUG) {
					Log.i("NO ALL PICK EVENT","Checked je FALSE");
				}
				if (all.isChecked())
				{
					// zrusime vyber vsech
					all.setChecked(false);

					// nastavime zpet stavy
					for (int i=0; zaskrtnute[i] > 0; i++)
					{
						CheckBox ch = (CheckBox) findViewById(zaskrtnute[i]);
						if (ch.getId() != btn.getId())
						{
							ch.setChecked(true);
						}
					}
				}
			}
		}
	}
	
	public class SaveOnClickListener implements OnClickListener 
	{ 
		public void onClick(View v) {
			
			// error text pro return
			String error = "\n";
			
			// objekty
			Spinner ridic_select = (Spinner) findViewById(R.id.driver_select);
			RadioButton tam_btn = (RadioButton) findViewById(R.id.tam);
			RadioButton zpet_btn = (RadioButton) findViewById(R.id.zpet);
			
			// kontrola checkboxu
			int passenger_count = 0;
			String[] passengers = new String[CHECKBOX_COUNT];
			for (int i=1; i<CHECKBOX_COUNT; i++)
			{
				CheckBox check = (CheckBox) findViewById(CHECKBOX_START_ID+i);
				if (check.isChecked())
				{
					passengers[passenger_count] = check.getText().toString();
					passenger_count ++;
				}
			}
			if (passenger_count == 0)
			{
				error += getString(R.string.err_no_passenger_selected)+"\n";
			}
			
			// kontrola zadani smeru
			TextView smer_view = null;
			if (tam_btn.isChecked()) {
				smer_view = (TextView) findViewById(R.id.tam_label);
			}
			else if (zpet_btn.isChecked()) {
				smer_view = (TextView) findViewById(R.id.zpet_label);
			}
			else
			{
				error += getString(R.string.err_no_direction_selected)+"\n";
			}
			
			// kontrola a pripadne vyhozeni ven
			if (!"\n".equals(error))
			{
				showToast(error);
				return;
			}
			
			// hodnoty k pouziti
			String ridic = ridic_select.getSelectedItem().toString();
			String smer = smer_view.getText().toString().trim();
			String datum = ""+getRok()+"-"+getCisloMesice()+"-"+getDen();
			
			db.open();
			Boolean splneno = db.saveDriveWay(ridic, datum, smer, passenger_count, passengers);
			db.close();
			
			String text;
			if (splneno) {
				text = getString(R.string.msg_driveway_saved);
			}
			else {
				text = getString(R.string.err_driveway_edit_disabled)+"\n"+getString(R.string.err_change_settings);
			}
			
			showToast(text);
			
			generateBilanceTables();
		}
	}
	
	public class RadioCheckChangedListener implements RadioGroup.OnCheckedChangeListener {

		public void onCheckedChanged(RadioGroup arg0, int arg1) {
			setDefaultValues();
		}
		
	}
	
	@Override
	public void zLevaDoPrava()
	{
		String text = prevMonth();
		showToast(text);
	}
	
	@Override
	public void zPravaDoLeva()
	{
		String text = nextMonth();
		showToast(text);
	}

	@Override
	public void zHoraDolu() {
		//showToast("Down Swipe");
	}

	@Override
	public void zDolaNahoru() {
		//showToast("Up Swipe");
	}
	
	public void pouzeClick(View v)
	{
		KalendarButton btn = (KalendarButton) v;
		int position = btn.position;
		
		setZobrazeno(KalendarTools.getDateOnPosition(zobrazeno.getTime(), position));
	}
	
	public void vlozDataZeSablonyDoDB()
	{	
		vlozNastaveniDoDB();
		
		db.open();
		
		long id;
		
		// u ridice se ulozi rovnou i kontakt
		id = db.insertDriver("Petr",30);
		id = db.insertDriver("Vendy",30);
		
		// kdo neridi, musi byt vytvoren jako pasazer
		id = db.insertContact("Tom");

		db.close();
	}
	
	private void vlozNastaveniDoDB()
	{
		db.open();
		
		//db.deleteAllSettings();
		
		long id;
		id = db.insertSetting("can_modify_way","true","set_can_modify_way");
		id = db.insertSetting("view_actual_month_only","true","set_view_actual_month_only");
		
		db.close();
	}

	private void generateLayout() 
	{
		// nastavit TABVIEW
		TabHost mTabHost = getTabHost();
		
		int height = 40;
		mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height = height;
		mTabHost.getTabWidget().getChildAt(1).getLayoutParams().height = height;
		mTabHost.getTabWidget().getChildAt(2).getLayoutParams().height = height;
		
		mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new TabViewChangeListener(0));
		mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new TabViewChangeListener(1));
		mTabHost.getTabWidget().getChildAt(2).setOnClickListener(new TabViewChangeListener(2));
        
        mTabHost.setCurrentTab(0);
		
		// nastavit combobox
		Spinner spinner = (Spinner) findViewById(R.id.driver_select);
		
		setDriversToSpinner(spinner);
		
		// nastavit tlacitka
		ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
		int position = 0;
		for (int i=1; i <= 6; i++)
		{
			for (String den: KalendarTools.dny)
			{
				String btn_id = den+"_"+i;
				
				int resID = getResources().getIdentifier(btn_id, "id", getPackageName());
				KalendarButton btn = (KalendarButton) findViewById(resID);				
				
				btn.position = position;
				//btn.setOnClickListener(new CalendarOnClickListener(position));
				btn.setOnTouchListener(activitySwipeDetector);
				
				position ++;
			}
		}
		
		// generovat checkboxy
		db.open();
		String[] passengers = db.getAllContacts();
		db.close();
		
		TableLayout table = (TableLayout) findViewById(R.id.check_table);
		table.removeAllViews();
		CHECKBOX_COUNT = 0;
		
		TableRow box_row = null;
		for (int i=0; i<=passengers.length; i++)
		{
			if (RideShareActivity.DEBUG) {
				Log.i("GENERATING CHECKBOXES", "Generuji checkbox cislo "+(i+1));
			}
			
			if (i % 2 == 0)
			{
				box_row = new TableRow(this);
				box_row.setId(ROW_START_ID+i);
				
				if (RideShareActivity.DEBUG) {
					Log.i("SELECT TABLE ROW", "Vybral jsem radek s ID: "+box_row.getId());
				}
//				label_row = new TableRow(this);
			}
			
			if (i == 0)
			{
				CheckBox all = new CheckBox(this);
					all.setId(CHECKBOX_START_ID);
					all.setWidth(CHECKBOX_WIDTH);
					all.setHeight(CHECKBOX_HEIGHT);
					all.setGravity(android.view.Gravity.CENTER);
					all.setText(getString(R.string.check_all));
					all.setOnCheckedChangeListener(new AllPickOnClickListener());
					
				if (RideShareActivity.DEBUG) {
					Log.i("CHECKBOX GENERATED", "All checkbox byl vygenerovan s ID: "+all.getId());
				}
				
				box_row.addView(all);
			}
			else
			{
				CheckBox cb = new CheckBox(this);
					cb.setId(CHECKBOX_START_ID+i);
					cb.setWidth(CHECKBOX_WIDTH);
					cb.setHeight(CHECKBOX_HEIGHT);
					cb.setGravity(android.view.Gravity.CENTER);
					cb.setText(passengers[i-1]);
					cb.setOnCheckedChangeListener(new NoAllPickOnClickListener());

				if (RideShareActivity.DEBUG) {
					Log.i("CHECKBOX GENERATED", ""+i+". checkbox byl vygenerovan s ID: "+cb.getId());
				}

				box_row.addView(cb);
			}

			if (RideShareActivity.DEBUG) {
				Log.i("UPDATE ROW", ""+i+". checkbox byl pridan do radku s ID: "+box_row.getId());
			}
			
			if (i % 2 == 1)
			{
				if (RideShareActivity.DEBUG) {
					Log.i("UPDATE TABLE", "Pridavam radek s ID: "+box_row.getId()+" do tabulky");
				}
				
				table.addView(box_row);
			}
			else if (i == passengers.length)
			{
				if (RideShareActivity.DEBUG) {
					Log.i("UPDATE TABLE", "Pridavam radek s ID: "+box_row.getId()+" do tabulky");
				}
				
				table.addView(box_row);
			}
			
			CHECKBOX_COUNT ++;
			if (RideShareActivity.DEBUG) {
				Log.i("CHECKBOX COUNT","(aktuální počet = "+CHECKBOX_COUNT+")");
			}
		}
		
		RadioButton tam_btn = (RadioButton) findViewById(R.id.tam);
		tam_btn.setChecked(true);
		RadioGroup smer = (RadioGroup) findViewById(R.id.smer);
		smer.setOnCheckedChangeListener((RadioGroup.OnCheckedChangeListener) new RadioCheckChangedListener());
		TextView tam_label = (TextView) findViewById(R.id.tam_label);
		TextView zpet_label = (TextView) findViewById(R.id.zpet_label);
		tam_label.setClickable(true);
		zpet_label.setClickable(true);
		tam_label.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				RadioButton tam_btn = (RadioButton) findViewById(R.id.tam);
				tam_btn.setChecked(true);
			}
		});
		zpet_label.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				RadioButton zpet_btn = (RadioButton) findViewById(R.id.zpet);
				zpet_btn.setChecked(true);
			}
		});

		Button save_btn = (Button) findViewById(R.id.save_day);
		save_btn.setOnClickListener(new SaveOnClickListener());
		
		// klikatko pro label jizdy
		TextView jizdy = (TextView) findViewById(R.id.show_jizdy);
		jizdy.setClickable(true);
		jizdy.setOnClickListener(new ShowJizdyListener());
		// klikatko pro label platby
		TextView platby = (TextView) findViewById(R.id.show_platby);
		platby.setClickable(true);
		platby.setOnClickListener(new ShowPlatbyListener());
	}
	
	public void generateSettings()
	{
		// pro pripadne nacteni zmen v nastavenich
		vlozNastaveniDoDB();
		
		// zjisteni hodnot v DB
		db.open();
		Setting[] set_params = db.getSettingsWithValues();
		String[] ridici = db.getAllDrivers();
		String[] kontakty = db.getAllContacts();
		db.close();
		
		TableLayout settings = (TableLayout) findViewById(R.id.tab3);
		
		settings.removeAllViews();
		
		settings.setFocusable(true);
		settings.setFocusableInTouchMode(true);
		TableRow row;
		View v;
		
		TableRow.LayoutParams col_span = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		col_span.span = 5;
		
		row = new TableRow(this);
			TextView note = new TextView(this);
			note.setText(getString(R.string.msg_settings_generated));
			note.setLayoutParams(col_span);
			row.addView(note);
			settings.addView(row);
			
		for (int i=0; i<set_params.length; i++)
		{
			Setting s = set_params[i];
			
			if (RideShareActivity.DEBUG) {
				Log.i("GENERATE_SETTINGS","Nalezeno: "+s.note);
			}
			
			row = new TableRow(this);
			CheckBox cb = new CheckBox(this);
			cb.setText(getString(getResources().getIdentifier(s.note, "string", getPackageName())));
			cb.setChecked(s.isset());
			cb.setOnCheckedChangeListener(new SettingChangeListener(s.name));
			cb.setLayoutParams(col_span);
			
			row.addView(cb);
			settings.addView(row);
			
			row = new TableRow(this);
			v = new View(this);
			v.setBackgroundColor(0xff909090);
			v.setLayoutParams(new LayoutParams(200, 10));
			row.addView(v);
			settings.addView(row);
		}
		
		// linka pro oddeleni struktury
		row = new TableRow(this);
			TableRow.LayoutParams p = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, 2);
			p.span = 4;//5;
			p.topMargin = 5;
			p.bottomMargin = 10;
			TextView view = new TextView(this);
				view.setBackgroundColor(0xff909090);
				view.setLayoutParams(p);
				view.setText("");
				view.setFocusable(true);
				view.setFocusableInTouchMode(true);
				view.setGravity(Gravity.CENTER);
			row.addView(view);
			settings.addView(row);
		
		// generování formu pro úpravy a přidávání kontaktů (řidičů)
		row = new TableRow(this);
			TextView nadpis = new TextView(this);
				nadpis.setWidth(95);
				nadpis.setText(getString(R.string.contact));
				nadpis.setFocusable(true);
				nadpis.setFocusableInTouchMode(true);
				nadpis.setGravity(Gravity.CENTER);
			row.addView(nadpis);
			
			nadpis = new TextView(this);
				nadpis.setWidth(45);
				nadpis.setText(getString(R.string.is_driver));
				nadpis.setFocusable(true);
				nadpis.setFocusableInTouchMode(true);
				nadpis.setGravity(Gravity.CENTER);
			row.addView(nadpis);
			
			nadpis = new TextView(this);
				nadpis.setWidth(60);
				nadpis.setText(getString(R.string.price));
				nadpis.setFocusable(true);
				nadpis.setFocusableInTouchMode(true);
				nadpis.setGravity(Gravity.CENTER);
			row.addView(nadpis);
			
			p = new TableRow.LayoutParams(100, LayoutParams.FILL_PARENT);
			p.span = 2;
			
			nadpis = new TextView(this);
				nadpis.setLayoutParams(p);
				nadpis.setText(getString(R.string.action));
				nadpis.setFocusable(true);
				nadpis.setFocusableInTouchMode(true);
				nadpis.setGravity(Gravity.CENTER);
			row.addView(nadpis);
			
			settings.addView(row);
		
		TableRow.LayoutParams cb_params = new TableRow.LayoutParams(45, LayoutParams.FILL_PARENT);
		cb_params.leftMargin = 5;
		for (int i=0; i<kontakty.length; i++)
		{
			row = new TableRow(this);
			
			EditText name = new EditText(this);
			name.setText(kontakty[i]);
			name.setEnabled(false);
			name.setId(SETTINGS_NAME_START_ID+i);
			name.setWidth(95);
			
			// vygeneruj checkbox ridice
			CheckBox cb = new CheckBox(this);
			// je-li ridic, zaskrtni checkbox
			cb.setChecked(inArray(ridici,kontakty[i]));
			cb.setEnabled(false);
			cb.setId(SETTINGS_DRIVER_CHECK_START_ID+i);
			cb.setLayoutParams(cb_params);
			
			EditText price = new EditText(this);
			price.setInputType(InputType.TYPE_CLASS_NUMBER);
			db.open();
			long driver = db.getDriverByName(kontakty[i]);
			int price_value;
			if (driver > 0) {
				price_value = db.getDriverPrice(driver);
			}
			else {
				price_value = 25;
			}
			db.close();
			price.setText(""+price_value);
			price.setEnabled(false);
			price.setId(SETTINGS_PRICE_START_ID+i);
			price.setWidth(60);
			
			TableRow.LayoutParams btn_params = new TableRow.LayoutParams(80, LayoutParams.FILL_PARENT);
			btn_params.topMargin = 1;
			Button btn = new Button(this);
			btn.setId(SETTINGS_EDIT_BTN_START_ID+i);
			btn.setLayoutParams(btn_params);
			btn.setOnClickListener(new EnableNamechangeListener(i));
			btn.setLongClickable(true);
			btn.setOnLongClickListener(new DeleteContactOnLongListener(i));
			btn.setText(getString(R.string.edit));
			btn.setGravity(Gravity.CENTER);
			btn.setBackgroundColor(0xff000000);
			btn.setTextColor(0xffffffff);
			
			/*
			TableRow.LayoutParams btn2_params = new TableRow.LayoutParams(40, LayoutParams.FILL_PARENT);
			btn_params.topMargin = 1;
			Button btn2 = new Button(this);
			btn2.setId(SETTINGS_EDIT_BTN2_START_ID+i);
			btn2.setLayoutParams(btn2_params);
			btn2.setOnClickListener(null);
			btn2.setText("-");
			btn2.setGravity(Gravity.CENTER);
			//btn2.setBackgroundResource(R.drawable.button_red);
			btn2.setBackgroundColor(0xff000000);
			btn2.setTextColor(0xffffffff);
			*/
			row.addView(name);
			row.addView(cb);
			row.addView(price);
			row.addView(btn);
			//row.addView(btn2);
			
			settings.addView(row);
		}
	}
	
	public class DeleteContactOnLongListener implements View.OnLongClickListener
	{
		int postition;
		
		public DeleteContactOnLongListener(int position)
		{
			this.postition = position;
		}

		public boolean onLongClick(View view) 
		{
			generateDeleteUserPopupWindow(postition);
			return true;
		}
	}
	
	public void generateDeleteUserPopupWindow(int i)
	{
		//showToast("Vygeneruji popup pro smazani uzivatele "+i,false);
		
		View layout = generateNovyCestujiciPopupWindow();
		
		EditText jmeno_input = (EditText) findViewById(SETTINGS_NAME_START_ID+i);
		CheckBox ridi_cb = (CheckBox) findViewById(SETTINGS_DRIVER_CHECK_START_ID+i);
		EditText cena_input = (EditText) findViewById(SETTINGS_PRICE_START_ID+i);
		
		Button btn_uloz = (Button) layout.findViewById(R.id.popup_uloz);
		EditText popup_jmeno = (EditText) layout.findViewById(R.id.popup_jmeno);
		CheckBox popup_ridi = (CheckBox) layout.findViewById(R.id.popup_ridi_check);
		EditText popup_cena = (EditText) layout.findViewById(R.id.popup_cena);
		TextView nadpis = (TextView) layout.findViewById(R.id.popup_nadpis);
		
		String jmeno = jmeno_input.getText().toString();
		
		popup_jmeno.setText(jmeno);
		popup_ridi.setChecked(ridi_cb.isChecked());
		popup_cena.setText(cena_input.getText());
		nadpis.setText(getString(R.string.msg_really_delete_passenger));
		
		popup_jmeno.setEnabled(false);
		popup_ridi.setEnabled(false);
		popup_cena.setEnabled(false);
		btn_uloz.setText(getString(R.string.delete));
		btn_uloz.setOnClickListener(new DeleteContactListener(jmeno));
	}
	
	public Boolean inArray(String[] array, String member)
	{
		for (int i=0; i<array.length; i++)
		{
			if (member.equals(array[i])) {
				return true;
			}
		}
		return false;
	}
	
	public Boolean isTrue(String value)
	{
		if ("true".equals(value)) {
			return true;
		}
		
		return false;
	}
	
	public void generateBilanceTables()
	{
		TableLayout table_jizdy = (TableLayout) findViewById(R.id.table_jizdy);
		TableLayout table_platby = (TableLayout) findViewById(R.id.table_platby);
		
		table_jizdy.removeAllViews();
		table_platby.removeAllViews();
		
		db.open();
		String[] ridici = db.getAllDrivers();
		String[] kontakty = db.getAllContacts();
		Boolean only_this_month = isTrue(db.getSetting("view_actual_month_only"));
		db.close();
		
		int poc_sloupcu = ridici.length + 1;
		TableRow.LayoutParams params;
		TableRow date_row = (TableRow) findViewById(R.id.tab2_date_row);
		TableRow space_row = (TableRow) findViewById(R.id.tab2_space_row);
		
		String datum = "";
		if (only_this_month)
		{
			// generujeme mesic a rok a tlacitka pro posun
			TextView date = (TextView) findViewById(R.id.tab2_date);
			date.setText(getMesic()+" "+getRok());
			date_row.setVisibility(android.view.View.VISIBLE);
			space_row.setVisibility(android.view.View.VISIBLE);
			
			// nastaveni listeneru
			TextView prev = (TextView) findViewById(R.id.tab2_date_prev);
			prev.setOnClickListener(new ChangeMonthListener("prev"));
			TextView next = (TextView) findViewById(R.id.tab2_date_next);
			next.setOnClickListener(new ChangeMonthListener("next"));
			
			// nastaveni prefixu datumu
			datum = getRok()+"-"+getCisloMesice();
		}
		else
		{
			date_row.setVisibility(android.view.View.GONE);
			space_row.setVisibility(android.view.View.GONE);
		}
		
		// generovani bilance jizd
		// radek s nadpisem bilance
		TableRow nadpis_jizdy_row = new TableRow(this);
			nadpis_jizdy_row.setBackgroundColor(TABLE_BACKGROUND);
		
		TextView nadpis_jizdy = new TextView(this);
			params = (TableRow.LayoutParams) new TableRow.LayoutParams();
			params.span = poc_sloupcu;
			params.width = ROW_WIDTH;
			params.setMargins(1, 1, 1, 1);
			nadpis_jizdy.setLayoutParams(params);
			nadpis_jizdy.setBackgroundColor(TITLE_BACKGROUND);
			nadpis_jizdy.setWidth(ROW_WIDTH);
			nadpis_jizdy.setGravity(android.view.Gravity.CENTER);
			nadpis_jizdy.setText(getString(R.string.title_way_bilance));
		
		nadpis_jizdy_row.addView(nadpis_jizdy);
		table_jizdy.addView(nadpis_jizdy_row);
		
		// nadpis se jmeny ridicu
		TableRow subnadpis_row = new TableRow(this);
			subnadpis_row.setBackgroundColor(TABLE_BACKGROUND);
		
		for (int i=0; i<poc_sloupcu; i++)
		{
			String text;
			if (i == 0) {
				text = getString(R.string.title_drivers)+":";
			}
			else {
				text = ridici[i-1];
			}
			
			CellText row_jizdy = new CellText(this);
				params = (TableRow.LayoutParams) new TableRow.LayoutParams();
				params.width = (int) ROW_WIDTH / poc_sloupcu - 2;
				params.height = ROW_HEIGHT;
				params.setMargins(1, 1, 1, 1);
				row_jizdy.setLayoutParams(params);
				row_jizdy.setTable_name("jizdy");
				if (i==0) {
					row_jizdy.setDriver("");
				}
				else {
					row_jizdy.setDriver(text);
				}
				row_jizdy.setPassenger("");
				row_jizdy.setClickable(true);
				row_jizdy.setOnClickListener(new CellOnClickListener());
				row_jizdy.setBackgroundColor(SUBTITLE_BACKGROUND);
				row_jizdy.setWidth((int) ROW_WIDTH / poc_sloupcu - 2);
				row_jizdy.setGravity(android.view.Gravity.CENTER);
				row_jizdy.setText(text);

			subnadpis_row.addView(row_jizdy);
		}
		table_jizdy.addView(subnadpis_row);
		
		// jednotlive radky
		for (int i=0; i<kontakty.length; i++)
		{
			TableRow row = new TableRow(this);
				row.setBackgroundColor(TABLE_BACKGROUND);
			
			for (int j=0; j<poc_sloupcu; j++)
			{
				String text;
				if (j == 0) {
					text = kontakty[i];
				}
				else
				{
					// zjisti pocet jizd pasazera s danym ridicem
					db.open();
					int poc_jizd = db.getWayCountWithDriver(kontakty[i],ridici[j-1],datum);
					db.close();
					text = ""+poc_jizd;
				}
				
				CellText row_cell = new CellText(this);
					params = (TableRow.LayoutParams) new TableRow.LayoutParams();
					params.width = (int) ROW_WIDTH / poc_sloupcu - 2;
					params.height = ROW_HEIGHT;
					params.setMargins(1, 1, 1, 1);
					row_cell.setTable_name("jizdy");
					row_cell.setLayoutParams(params);
					if (j==0) {
						row_cell.setDriver("");
					}
					else {
						row_cell.setDriver(ridici[j-1]);
					}
					row_cell.setPassenger(kontakty[i]);
					row_cell.setClickable(true);
					row_cell.setOnClickListener(new CellOnClickListener());
				// POZOR!!! podminka se nesmi prehodit
				if (j != 0 && kontakty[i].equals(ridici[j-1])) {
					row_cell.setBackgroundColor(SUBTITLE_BACKGROUND);
				}
				else {
					row_cell.setBackgroundColor(CELL_BACKGROUND);
				}
					row_cell.setWidth((int) ROW_WIDTH / poc_sloupcu - 2);
					row_cell.setGravity(android.view.Gravity.CENTER);
					row_cell.setText(text);

				row.addView(row_cell);
			}
			
			table_jizdy.addView(row);
		}
		
		// generovani bilance plateb
		// radek s nadpisem bilance
		TableRow nadpis_platby_row = new TableRow(this);
			nadpis_platby_row.setBackgroundColor(TABLE_BACKGROUND);
		
		TextView nadpis_platby = new TextView(this);
			params = (TableRow.LayoutParams) new TableRow.LayoutParams();
			params.span = poc_sloupcu;
			params.width = ROW_WIDTH;
			params.setMargins(1, 1, 1, 1);
			nadpis_platby.setLayoutParams(params);
			nadpis_platby.setBackgroundColor(TITLE_BACKGROUND);
			nadpis_platby.setWidth(ROW_WIDTH);
			nadpis_platby.setGravity(android.view.Gravity.CENTER);
			nadpis_platby.setText(getString(R.string.title_payment_bilance));
		
		nadpis_platby_row.addView(nadpis_platby);
		table_platby.addView(nadpis_platby_row);
		
		// nadpis se jmeny ridicu
		subnadpis_row = new TableRow(this);
			subnadpis_row.setBackgroundColor(TABLE_BACKGROUND);
		
		for (int i=0; i<poc_sloupcu; i++)
		{
			String text;
			if (i == 0) {
				text = getString(R.string.title_drivers)+":";
			}
			else {
				text = ridici[i-1];
			}
			
			CellText row_platby = new CellText(this);
				params = (TableRow.LayoutParams) new TableRow.LayoutParams();
				params.width = (int) ROW_WIDTH / poc_sloupcu - 2;
				params.height = ROW_HEIGHT;
				params.setMargins(1, 1, 1, 1);
				row_platby.setLayoutParams(params);
				row_platby.setTable_name("platby");
				if (i==0) {
					row_platby.setDriver("");
				}
				else {
					row_platby.setDriver(text);
				}
				row_platby.setPassenger("");
				row_platby.setClickable(true);
				row_platby.setOnClickListener(new CellOnClickListener());
				row_platby.setBackgroundColor(SUBTITLE_BACKGROUND);
				row_platby.setWidth((int) ROW_WIDTH / poc_sloupcu - 2);
				row_platby.setGravity(android.view.Gravity.CENTER);
				row_platby.setText(text);

			subnadpis_row.addView(row_platby);
		}
		table_platby.addView(subnadpis_row);
		
		// jednotlive radky
		for (int i=0; i<kontakty.length; i++)
		{
			TableRow row = new TableRow(this);
				row.setBackgroundColor(TABLE_BACKGROUND);
			
			for (int j=0; j<poc_sloupcu; j++)
			{
				String text;
				if (j == 0) {
					text = kontakty[i];
				}
				else
				{
					// zjisti pocet jizd pasazera s danym ridicem
					db.open();
					int castka = db.getAmountToPayWithDriver(kontakty[i],ridici[j-1]);
					db.close();
					text = ""+castka;
				}
				
				CellText row_cell = new CellText(this);
					params = (TableRow.LayoutParams) new TableRow.LayoutParams();
					params.width = (int) ROW_WIDTH / poc_sloupcu - 2;
					params.height = ROW_HEIGHT;
					params.setMargins(1, 1, 1, 1);
					row_cell.setLayoutParams(params);
					row_cell.setTable_name("platby");
					if (j==0) {
						row_cell.setDriver("");
					}
					else {
						row_cell.setDriver(ridici[j-1]);
					}
					row_cell.setPassenger(kontakty[i]);
					row_cell.setClickable(true);
					row_cell.setOnClickListener(new CellOnClickListener());
				// POZOR!!! podminka se nesmi prehodit
				if (j != 0 && kontakty[i].equals(ridici[j-1])) {
					row_cell.setBackgroundColor(SUBTITLE_BACKGROUND);
				}
				else {
					row_cell.setBackgroundColor(CELL_BACKGROUND);
				}
					row_cell.setWidth((int) ROW_WIDTH / poc_sloupcu - 2);
					row_cell.setGravity(android.view.Gravity.CENTER);
					row_cell.setText(text);

				row.addView(row_cell);
			}
			
			table_platby.addView(row);
		}
	}
	
	public void generateBilanceHistory(String table_name)
	{
		int datum_width = 90;
		int smer_width = 20;
		int kdo_komu_kolik_width = 60;
		
		if ("jizdy".equals(table_name))
		{
			// Jizdy
			TableRow jizdy_row = (TableRow) findViewById(R.id.history_jizdy);
			
			// je-li jiz vykreslena, musime ji skryt a znicit vsechny prvky
			if (HISTORY_JIZDY_VISIBLE)
			{
				jizdy_row.removeAllViews();
				HISTORY_JIZDY_VISIBLE = false;
				//return;
			}
			else
			{
				TableLayout table = new TableLayout(this);
				TableRow table_row;
				TextView smer;
				TextView datum;
				LinearLayout pasazeri;
				TextView jmeno;
				String date_prefix;

					if (RideShareActivity.DEBUG) {
						Log.i("GENERATE HISTORY","Vybereme vsechny jizdy serazene podle data");
					}
					
					db.open();
					
					Boolean only_this_month = isTrue(db.getSetting("view_actual_month_only"));
					// prefix pro hledani jizd pouze v danem mesici
					if (only_this_month) {
						date_prefix = getRok()+"-"+getCisloMesice();
					}
					else {
						date_prefix = "";
					}
					
					ArrayList<Driveway> ways = db.getAllWays(HISTORY_DRIVER,HISTORY_PASSENGER,date_prefix);
					db.close();
					if (ways == null)
					{
						if (RideShareActivity.DEBUG) {
							Log.i("GENERATE HISTORY","Žádná jízda k vykreslení");
						}
						showToast(getString(R.string.msg_no_driveway_to_show), false);
						return;
					}
					
					if (RideShareActivity.DEBUG) {
						Log.i("GENERATE HISTORY","Existuje "+ways.size()+" jízd");
					}

					for (int i=0; i<ways.size(); i++)
					{
						Driveway w = ways.get(i);

						table_row = new TableRow(this);

						smer = new TextView(this);
							smer.setWidth(smer_width);
							if (getString(R.string.direction_forward).equals(w.smer))
							{
								smer.setTextColor(0xff0000ff);
								smer.setText("=>");
							}
							else
							{
								smer.setTextColor(0xffff0000);
								smer.setText("<=");
							}
						datum = new TextView(this);
							datum.setWidth(datum_width);
							datum.setText(w.datum);
						pasazeri = new LinearLayout(this);
						if (RideShareActivity.DEBUG) {
							Log.i("GENERATE HISTORY","Poč. pasažérů: "+(w.pasazeri.length+1)/2);
						} // kvuli carkam mezi jmeny
						String pas_all = "";
						for (int j=0; j<w.pasazeri.length; j++)
						{
							String p = w.pasazeri[j];
							pas_all += p;

							jmeno = new TextView(this);
							if (p == null ? w.ridic == null : p.equals(w.ridic)) {
								jmeno.setTextColor(0xffff0000);
							}
							jmeno.setText(p);
							pasazeri.addView(jmeno);
						}

						if (RideShareActivity.DEBUG) {
							Log.i("GENERATE HISTORY","Jízda ("+w.datum+","+w.smer+","+pas_all+")");
						}

						table_row.addView(smer);
						table_row.addView(datum);
						table_row.addView(pasazeri);

						table.addView(table_row);
					}

				jizdy_row.addView(table);
				
				HISTORY_JIZDY_VISIBLE = true;
			}
		}
		else if ("platby".equals(table_name))
		{
			// Platby
			TableRow platby_row = (TableRow) findViewById(R.id.history_platby);
			
			// je-li jiz vykreslena, musime ji skryt a znicit vsechny prvky
			if (HISTORY_PLATBY_VISIBLE)
			{
				platby_row.removeAllViews();
				HISTORY_PLATBY_VISIBLE = false;
				//return;
			}
			else
			{
				TableLayout table = new TableLayout(this);
				TableRow table_row;
				TextView datum;
				TextView kdo;
				TextView komu;
				TextView kolik;
				TextView sipka;
				TextView pozn;

					if (RideShareActivity.DEBUG) {
					Log.i("GENERATE HISTORY","Vybereme vsechny platby serazene podle data");
				}

					db.open();
					ArrayList<Payment> payments = db.getAllPayments(HISTORY_DRIVER, HISTORY_PASSENGER);
					db.close();
					if (payments == null)
					{
						if (RideShareActivity.DEBUG) {
							Log.i("GENERATE HISTORY","Žádná platba k vykreslení");
						}
						showToast(getString(R.string.msg_no_payment_to_show), false);
						return;
					}
					
					if (RideShareActivity.DEBUG) {
						Log.i("GENERATE HISTORY","Existuje "+payments.size()+" plateb");
					}

					for (int i=0; i<payments.size(); i++)
					{
						Payment p = payments.get(i);

						table_row = new TableRow(this);

						datum = new TextView(this);
							datum.setWidth(datum_width);
							datum.setText(p.datum);
						kdo = new TextView(this);
							kdo.setWidth(kdo_komu_kolik_width);
							kdo.setText(p.kdo);
						sipka = new TextView(this);
							sipka.setWidth(smer_width);
							sipka.setText("=>");
							sipka.setTextColor(0xffff0000);
						komu = new TextView(this);
							komu.setWidth(kdo_komu_kolik_width);
							komu.setText(p.komu);
						kolik = new TextView(this);
							kolik.setWidth(kdo_komu_kolik_width);
							kolik.setText(p.kolik+getString(R.string.currency));

						if (RideShareActivity.DEBUG) {
							Log.i("GENERATE HISTORY","Platba ("+p.datum+","+p.kdo+","+p.komu+","+p.kolik+" - "+p.pozn+")");
						}

						table_row.addView(datum);
						table_row.addView(kdo);
						table_row.addView(sipka);
						table_row.addView(komu);
						table_row.addView(kolik);
						
						table_row.setClickable(true);
						table_row.setOnClickListener(new ShowNoteListener(p.pozn));

						table.addView(table_row);
					}

				platby_row.addView(table);
				
				HISTORY_PLATBY_VISIBLE = true;
			}
		}
	}
	
	public void generateNovaPlatbaPopupWindow()
	{
		LayoutInflater inflater = (LayoutInflater) RideShareActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //Inflate the view from a predefined XML layout
        View layout = inflater.inflate(R.layout.platba_popup_layout,
                (ViewGroup) findViewById(R.id.platba_popup_layout));
        // create a 300px width and 470px height PopupWindow
        popup_window = new PopupWindow(layout, 320, 480, true);
        // display the popup in the center
        popup_window.showAtLocation(layout, Gravity.BOTTOM, 0, 0);

		EditText input;
		Spinner select;
		
		input = (EditText) layout.findViewById(R.id.popup_datum);
		input.setText(getDen()+"."+getCisloMesice()+". "+getRok());
		input.setFocusable(false);

		select = (Spinner) layout.findViewById(R.id.popup_contact_paying);
		setContactsToSpinner(select);

		select = (Spinner) layout.findViewById(R.id.popup_contact_receiving);
		setContactsToSpinner(select);
		
		input = (EditText) layout.findViewById(R.id.popup_amount);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		
		Button save = (Button) layout.findViewById(R.id.popup_save);
		save.setOnClickListener(new SavePaymentListener());
		Button cancel = (Button) layout.findViewById(R.id.popup_cancel);
		cancel.setOnClickListener(new PopupCancelListener());
	}
	
	public View generateNovyCestujiciPopupWindow()
	{
		LayoutInflater inflater = (LayoutInflater) RideShareActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //Inflate the view from a predefined XML layout
        View layout = inflater.inflate(R.layout.cestujici_popup_layout,
                (ViewGroup) findViewById(R.id.cestujici_popup_layout));
        // create a 300px width and 470px height PopupWindow
        popup_window = new PopupWindow(layout, 320, 480, true);
        // display the popup in the center
        popup_window.showAtLocation(layout, Gravity.BOTTOM, 0, 0);

		EditText input;
		CheckBox checkbox;
		
		input = (EditText) layout.findViewById(R.id.popup_jmeno);
		input.setText("");
		
		input = (EditText) layout.findViewById(R.id.popup_cena);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		input.setText("25");
		input.setEnabled(false);

		checkbox = (CheckBox) layout.findViewById(R.id.popup_ridi_check);
		checkbox.setChecked(false);
		checkbox.setOnCheckedChangeListener(new RidiOnCheckListener(input));
		
		Button save = (Button) layout.findViewById(R.id.popup_uloz);
		save.setOnClickListener(new UlozCestujicihoListener());
		Button cancel = (Button) layout.findViewById(R.id.popup_zrus);
		cancel.setOnClickListener(new PopupCancelListener());
		
		return layout;
	}
	
	public class RidiOnCheckListener implements OnCheckedChangeListener
	{
		EditText cena;
		
		public RidiOnCheckListener(EditText cena)
		{
			super();
			this.cena = cena;
		}
		
		public void onCheckedChanged(CompoundButton btn, boolean checked) 
		{
			cena.setEnabled(checked);
		}
	}
	
	public class ShowJizdyListener implements OnClickListener
	{
		public void onClick(View arg0) {
			
			generateBilanceHistory("jizdy");
		}
	}
	
	public class ShowPlatbyListener implements OnClickListener
	{
		public void onClick(View arg0) 
		{
			generateBilanceHistory("platby");
		}
	}
	
	public class CellOnClickListener implements OnClickListener
	{
		public void onClick(View v)
		{
			CellText cell = (CellText) v;
			
			HISTORY_DRIVER = cell.driver;
			HISTORY_PASSENGER = cell.passenger;
			
			if ("jizdy".equals(cell.table_name))
			{
				if (HISTORY_JIZDY_VISIBLE) {
					generateBilanceHistory(cell.table_name);
				}
				generateBilanceHistory(cell.table_name);
			}
			if ("platby".equals(cell.table_name))
			{
				if (HISTORY_PLATBY_VISIBLE) {
					generateBilanceHistory(cell.table_name);
				}
				generateBilanceHistory(cell.table_name);
			}
		}
	}
	
	public class ProvedPlatbuMenuListener implements OnMenuItemClickListener
	{
		public boolean onMenuItemClick(MenuItem menu) {
			//showToast("Stisknuto menu "+menu.toString(), false);

			generateNovaPlatbaPopupWindow();
		
			return true;
		}
	}
	
	public class NovyCestujiciMenuListener implements OnMenuItemClickListener
	{
		public boolean onMenuItemClick(MenuItem menu) {
			//showToast("Stisknuto menu "+menu.toString(), false);

			View layout = generateNovyCestujiciPopupWindow();
		
			return true;
		}
	}
	
	public class SavePaymentListener implements OnClickListener
	{
		public void onClick(View v) {
			
			View view = popup_window.getContentView();
			
			Spinner contact_paying = (Spinner) view.findViewById(R.id.popup_contact_paying);
			Spinner contact_receiving = (Spinner) view.findViewById(R.id.popup_contact_receiving);
			TextView amount = (TextView) view.findViewById(R.id.popup_amount);
			EditText note = (EditText) view.findViewById(R.id.popup_note);
			
			String paying_name = contact_paying.getSelectedItem().toString();
			String receiving_name = contact_receiving.getSelectedItem().toString();
			String amount_text = amount.getText().toString();
			
			String error = "\n";
			
			int amount_value = 0;
			if (!"".equals(amount_text)) {
				amount_value = Integer.parseInt(amount.getText().toString());
			}
			
			if (paying_name.equals(receiving_name))
			{
				error += getString(R.string.err_same_names)+"\n";
			}
			if (amount_value == 0)
			{
				error += getString(R.string.err_null_amount)+"\n";
			}
			
			if (!"\n".equals(error))
			{
				showToast(error, false);
				return;
			}
			
			String datum = getRok()+"-"+getCisloMesice()+"-"+getDen();
			
			db.open();
			Long retval = db.insertPayment(datum, receiving_name, paying_name, amount_value, note.getText().toString());
			db.close();
			
			if (retval > 0) {
				showToast(getString(R.string.msg_payment_saved,paying_name,receiving_name,amount_value)+getString(R.string.currency));
			}
			else {
				showToast(getString(R.string.msg_payment_not_saved));
			}
			
			generateBilanceTables();
			generateBilanceHistory("platby");
			popup_window.dismiss();
		}
	}
	
	public class UlozCestujicihoListener implements OnClickListener
	{
		public void onClick(View v) {
			
			View view = popup_window.getContentView();
			
			EditText jmeno_input = (EditText) view.findViewById(R.id.popup_jmeno);
			EditText cena_input = (EditText) view.findViewById(R.id.popup_cena);
			CheckBox ridi_input = (CheckBox) view.findViewById(R.id.popup_ridi_check);
			
			Boolean ridi = ridi_input.isChecked();
			String jmeno = jmeno_input.getText().toString();
			int cena = 0;
			if (ridi) {
				cena = Integer.parseInt(cena_input.getText().toString());
			}
			
			String error = "\n";
			
			if (ridi && cena == 0)
			{
				error += getString(R.string.err_null_amount)+"\n";
			}
			
			if (!"\n".equals(error))
			{
				showToast(error, false);
				return;
			}
			
			Long retval;
			
			db.open();
			if (ridi) {
				retval = db.insertDriver(jmeno, cena);
			}
			else {
				retval = db.insertContact(jmeno);
			}
			db.close();
			
			if (retval > 0) {
				showToast(getString(R.string.msg_contact_saved, jmeno), false);
			}
			else {
				showToast(getString(R.string.msg_contact_not_saved), false);
			}
			
			generateLayout();
			setDefaultValues();
			generateBilanceTables();
			generateSettings();
			popup_window.dismiss();
		}
	}
	
	public class PopupCancelListener implements OnClickListener
	{
		public void onClick(View v) {
			popup_window.dismiss();
		}
	}
	
	public class UkoncitMenuListener implements OnMenuItemClickListener
	{
		public boolean onMenuItemClick(MenuItem menu) {
			showToast(getString(R.string.title_app_quit), false);
			
			System.runFinalizersOnExit(true);
			System.exit(0);
			
			return true;
		}
	}
	
	public class SettingChangeListener implements OnCheckedChangeListener {

		String name;
		
		public SettingChangeListener(String name)
		{
			super();
			this.name = name;
		}
		
		public void onCheckedChanged(CompoundButton btn, boolean checked) {
			
			String value = "false";
			if (checked) {
				value = "true";
			}
			db.open();
			Boolean result = db.set(name,value);
			db.close();
			
			if (result) {
				showToast(getString(R.string.msg_settings_changed), false);
			}
			else {
				showToast(getString(R.string.error)+"\n"+getString(R.string.msg_settings_not_changed), false);
			}
		}
	}
	
	public class ShowNoteListener implements OnClickListener
	{
		public String text;
		
		public ShowNoteListener(String text)
		{
			this.text = getString(R.string.note)+": "+text;
		}
		
		public void onClick(View arg0) 
		{
			showToast(this.text);
		}
	}
	
	public void showToast(String text)
	{
		showToast(text, true);
	}
	
	public void showToast(String text, boolean dlouhy)
	{
		int delka = dlouhy ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
		
		Toast toast = Toast.makeText(RideShareActivity.this, text, delka);
		
		toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}
	
	public class DeleteContactListener implements OnClickListener 
	{
		// musi se pricist k startovnimu ID
		public String name;
		
		public DeleteContactListener(String name)
		{
			this.name = name;
		}
		
		public void onClick(View v) 
		{
			//showToast("Smažu kontakt se jménem "+name, false);
			
			db.open();
			BooleanMesssage deleted = db.deleteDriver(name, true);
			db.close();
			
			showToast(deleted.getMsg());
			
			if (deleted.isOK()) {
				generateSettings();
			}
			
			popup_window.dismiss();
		}
	}
	
	public class EnableNamechangeListener implements OnClickListener 
	{
		// musi se pricist k startovnimu ID
		public int position;
		
		public EnableNamechangeListener(int position)
		{
			this.position = position;
		}
		
		public void onClick(View v) 
		{
			EditText name = (EditText) findViewById(SETTINGS_NAME_START_ID+position);
			CheckBox cb = (CheckBox) findViewById(SETTINGS_DRIVER_CHECK_START_ID+position);
			Button btn = (Button) findViewById(SETTINGS_EDIT_BTN_START_ID+position);
			EditText price = (EditText) findViewById(SETTINGS_PRICE_START_ID+position);
			
			if (name.isEnabled())
			{
				// provedeme ulozeni a prepnuti na disabled
				db.open();
				Boolean done = db.updateContactName(position,name.getText().toString(),cb.isChecked(),Integer.parseInt(price.getText().toString()));
				db.close();
				
				if (done)
				{
					// zmena zobrazeni
					name.setEnabled(false);
					name.clearFocus();
					cb.setEnabled(false);
					btn.setText(getString(R.string.edit));
					price.setEnabled(false);

					showToast(getString(R.string.msg_changes_applied), false);
				}
				else
				{
					showToast(getString(R.string.msg_changes_not_applied), false);
				}
			}
			else
			{
				// provedeme prepnuti na enabled
				name.setEnabled(true);
				cb.setEnabled(true);
				btn.setText(getString(R.string.save));
				price.setEnabled(true);
				// pokud neni zadana cena, napis tam 25
				if ("".equals(price.getText().toString())) {
					price.setText("25");
				}
			}
		}
	}
	
	public class TabViewChangeListener implements OnClickListener
	{
		public int index;

		public TabViewChangeListener(int index) {
			this.index = index;
		}
		
		public void onClick(View v) 
		{
			switch (index)
			{
				case TAB_JIZDY:
					generateLayout();
					setDefaultValues();
					//showToast("Jsem na kalendáři jízd", false);
					break;
				case TAB_PENIZE:
					generateBilanceTables();
					if (HISTORY_JIZDY_VISIBLE) {
						generateBilanceHistory("jizdy");
					}
					if (HISTORY_PLATBY_VISIBLE) {
						generateBilanceHistory("platby");
					}
					//showToast("Jsem na bilancích", false);
					break;
				case TAB_NASTAVENI:
					generateSettings();
					//showToast("Jsem na nastavení", false);
					break;
			}
			
			getTabHost().setCurrentTab(index);
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		
		generateLayout();
		generateSettings();
		generateBilanceTables();
	}
}
